package com.example.wifistatedemo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.support.v7.app.ActionBarActivity;
import android.text.style.SuperscriptSpan;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity implements OnClickListener{
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		// if (receiver.isInitialStickyBroadcast()) {
		// unregisterReceiver(receiver);
		// }
		//
		 super.onDestroy();
	}

	private static final String TAG = MainActivity.class.getSimpleName();
	private static final String ACTION = "android.net.wifi.WIFI_STATE_CHANGED";
	private Button showWifiBtn;
	private Button changeWifiBtn;
	private TextView curStateTX;
	private Context mContext = MainActivity.this;
	private WifiManager wm;
	private ListView wifiListView;
	private List<ScanResult> wifiList;
	public static WifiAdapter mAdapter;
	private NetworkInfo mNetworkInfo;
	private ConnectivityManager conManager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		wm = (WifiManager) mContext.getSystemService(mContext.WIFI_SERVICE);
		conManager = (ConnectivityManager) mContext.getSystemService(CONNECTIVITY_SERVICE);

		initView();

		showWifiList();

	}

	private void initView() {
		// TODO Auto-generated method stub
		setTitle(getResources().getString(R.string.actionbar_title));

		showWifiBtn = (Button) findViewById(R.id.show_wifi);
		changeWifiBtn = (Button) findViewById(R.id.change_wifi);
		curStateTX = (TextView) findViewById(R.id.cur_info);
		wifiListView = (ListView) findViewById(R.id.wifi_listview);

		mAdapter = new WifiAdapter();
		wifiListView.setAdapter(mAdapter);

		showWifiBtn.setOnClickListener(this);
		changeWifiBtn.setOnClickListener(this);
		wifiListView.setOnItemClickListener(new WifiListener());
	}

	/**
	 * @author 909584 ListView的点击事件监听器
	 */
	private class WifiListener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			// 获取手机中保存的wifi列表
			List<WifiConfiguration> configList = wm.getConfiguredNetworks();
			String clickedWifi = mAdapter.getItem(position).SSID;
			// 判断选中的wifi是否保存在列表中
			if (null != isClickedExist(clickedWifi, configList)) {
				Ilog("在列表中找到了目标wifi");
				connectNetwork(isClickedExist(clickedWifi, configList));
			} else {
				Toast("未找到目标wifi，手动进行配置");
			}

		}

	}

	/**
	 * 显示wifi列表
	 */
	private void showWifiList() {
		wm.startScan();// 开始扫描wifi信号
		wifiList = wm.getScanResults();// 获取扫描到的wifi列表
		Ilog("wifi列表的大小为 : " + wifiList.size() + wifiList.get(0).SSID);
		mAdapter.setmList(wifiList);
		mAdapter.notifyDataSetChanged();
	}

	/**
	 * 连接目标网络
	 * 
	 * @param configuration
	 */
	public void connectNetwork(WifiConfiguration configuration) {
		// TODO Auto-generated method stub
		Ilog("netId = " + configuration.networkId);
		
		WifiChangeReceiver receiver = new changeReceiver();

		// 连接网络的同时，注册广播接收器，接收系统改变Wifi时的Intent
		IntentFilter filter = new IntentFilter();
		filter.addAction(ACTION);
		filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		registerReceiver(receiver, filter);

		// 连接选中的网络语句
		wm.enableNetwork(configuration.networkId, true);
	}

	/**
	 * 判断被点中的wifi是否在configedNetworks列表中
	 * 
	 * @param clickedWifi
	 *            目标wifi的ssid
	 * @param configList
	 */
	public WifiConfiguration isClickedExist(String clickedWifi, List<WifiConfiguration> configList) {

		for (int i = 0; i < configList.size(); i++) {

			Ilog("clickedwifi = " + clickedWifi + "??" + " list = " + configList.get(i).SSID.replace("\"", ""));
			if (clickedWifi.equals(configList.get(i).SSID.replace("\"", ""))) {
				return configList.get(i);
			} else {

			}
		}
		return null;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.show_wifi:
			Ilog("点击show_wifi按钮");
			showWifiInfo();
			break;

		case R.id.change_wifi:
			Ilog("点击change_wifi按钮");
			changeWifi();
			break;

		default:
			break;
		}
	}

	/**
	 * 显示wifi状态信息和wifi的名称
	 */
	private void showWifiInfo() {
		// 判断wifi功能是否被开启
		if (wm.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
			getWifiInfo();
			Ilog("wifi开关状态为--->开");
			Ilog("当前wifi的详细信息 : " + mNetworkInfo.getState());
			Ilog("当前连接的wifi为--->" + mNetworkInfo.getExtraInfo());
			Ilog("连接状态为--->" + mNetworkInfo.getState());

			curStateTX.setText(getResources().getString(R.string.current_wifi_info) + mNetworkInfo.getExtraInfo());
		} else {
			Toast.makeText(mContext, "wifi功能被关闭", Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 获取wifi的信息
	 */
	private void getWifiInfo() {
		// TODO Auto-generated method stub
		mNetworkInfo = conManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

		// 获取手机中保存的wifi列表
		// List<WifiConfiguration> configList = wm.getConfiguredNetworks();
		// for (int i = 0; i < configList.size(); i++) {
		// Ilog("configList循环--" + i + "--->" + configList.get(i).SSID);
		// }
	}

	/**
	 * 跳转到另一个wifi上
	 */
	private void changeWifi() {

	}

	/**
	 * @author 909584 wifi名称列表使用的适配器
	 */
	private class WifiAdapter extends BaseAdapter {

		private List<ScanResult> mList = new ArrayList<ScanResult>();

		public void setmList(List<ScanResult> list) {
			this.mList = list;
		}

		@Override
		public int getCount() {
			Ilog("getCount--->" + mList.size());
			return mList.size();
		}

		@Override
		public ScanResult getItem(int position) {
			// TODO Auto-generated method stub
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.listview_item, null);
				holder = new ViewHolder();
				holder.wifiName = (TextView) convertView.findViewById(R.id.ssid_tv);
				holder.wifiState = (TextView) convertView.findViewById(R.id.state_tv);
				convertView.setTag(holder);
			} else {
				// 注意，这个强制转换一定要写，否则报错
				holder = (ViewHolder) convertView.getTag();
			}

			if (mList.get(position) != null && mNetworkInfo != null) {
				holder.wifiName.setText("" + mList.get(position).SSID);
				// 去除wifi名称中的双引号
				String currentWifi = mNetworkInfo.getExtraInfo().replace("\"", "");
				Ilog("currentWifi = " + currentWifi + " || mList = " + mList.get(position).SSID);
				if (currentWifi.equals(mList.get(position).SSID)) {
					holder.wifiState.setText("Connected");
					Ilog("SET CONNECTED STRING");
				} else {
					holder.wifiState.setText("");
					Ilog("HIDE CONNECTED STRING");
				}
			} else {
				holder.wifiName.setText("");
				holder.wifiState.setText("");
			}

			return convertView;
		}

	}
	
	/**
	 * @author 909584
	 * 继承WifiChangeReceiver的onReceive方法，再添加刷新视图的方法
	 */
	private class changeReceiver extends WifiChangeReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			super.onReceive(context, intent);
			getWifiInfo();
			mAdapter.notifyDataSetChanged();
		}
		
	}

	class ViewHolder {
		TextView wifiName;
		TextView wifiState;
	}

	private void Ilog(String str) {
		Log.i(TAG, str);
	}

	private void Toast(String str) {
		Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
